// src/utils/request.js
import axios from "axios";
// 创建 axios 实例
const instance = axios.create({
  baseURL: 'http://www.cirno.asia:8080',
  timeout: 10000, // 请求超时时间
  headers: {
    "Content-Type": "application/json",
  },
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 可在这里添加 Token 认证
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    if(response.data.code ===403||response.data.code === 401 ||response.data.code === 400){
      window.localStorage.removeItem('token')
      window.localStorage.setItem('isLogin',false)
      window.history.replaceState(null, '', '/login')
      alert('登录信息已过期，请重新登录')
      window.location.reload()
    }
    if(response.headers['authorization']){
      window.localStorage.setItem('token',response.headers['authorization'])
    }
    return response.data;
  },
  (error) => {
    console.error("API 请求出错:", error);
    return Promise.reject(error);
  }
);

export default instance;
